package com.ruoyi.project.cyq.task.task.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.cyq.task.task.domain.Leave;
import com.ruoyi.project.cyq.task.task.domain.Status;
import com.ruoyi.project.cyq.task.task.domain.Task;
import com.ruoyi.project.cyq.task.task.domain.TaskVo;
import com.ruoyi.project.cyq.task.task.mapper.LeaveMapper;
import com.ruoyi.project.cyq.task.task.mapper.StatusMapper;
import com.ruoyi.project.cyq.task.task.service.ITaskService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cyq/task/task")
public class TaskController extends BaseController {


    private String prefix = "cyq/task/task";

    @Autowired
    private ITaskService iTaskService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IDeptService iDeptService;

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private StatusMapper statusMapper;

    /**
     * 跳转task页面
     *
     * @return
     */
    @RequiresPermissions("cyq:task:view")
    @GetMapping()
    public String operlog() {
        return prefix + "/task";
    }






    @RequiresPermissions("cyq:task:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Task task) {
        startPage();
        List<TaskVo> list = iTaskService.selectTaskList(task);
        return getDataTable(list);
    }

    /**
     * 跳转添加页面
     * @param modelMap
     * @return
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Dept dept = new Dept();
        List<Dept> depts = iDeptService.selectDeptList(dept);
        modelMap.addAttribute("depts", depts);
        return prefix + "/add";
    }


    /**
     * 根据部门查询User/回显所有部门
     * @param deptId
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectUserByDept")
    public String selectUserByDept(String deptId) {
        User user = new User();
        user.setDeptId(Long.valueOf(deptId));
        List<User> users = iUserService.selectUserList(user);
        return JSON.toJSONString(users);
    }

    /**
     * 添加任务
     * @param task
     * @param taskStartTime
     * @param taskEndTime
     * @param loginUser
     * @return
     */
    @RequiresPermissions("cyq:task:add")
    @Log(title = "任务管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Task task, String taskStartTime, String taskEndTime,String loginUser) {
        task.setTaskIssueUserId(1);
        task.setTaskStatus(1);
        if (UserConstants.CYQ_TASK_TITLE_NOT_UNIQUE.equals(iTaskService.checkTaskNameUnique(task))) {
            return error("任务创建'" + task.getTaskTitle() + "'失败，任务标题已存在");
        }
        return toAjax(iTaskService.insertTask(task, taskStartTime, taskEndTime));
    }

    /**
     * 校验公告类型名称
     */
    @PostMapping("/checkTaskNameUnique")
    @ResponseBody
    public String checkTaskNameUnique(Task task) {
        return iTaskService.checkTaskNameUnique(task);
    }

    /**
     * 修改岗位
     */
    @GetMapping("/edit/{taskId}")
    public String edit(@PathVariable("taskId") long taskId, ModelMap mmap) {
        //根据Id查询Task
        Task task = iTaskService.selectTaskById(taskId);

        //回显一个任务
        mmap.put("task", task);

        //回显Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mmap.put("taskStartTimeStr", this.convertDate1(task.getTaskStartTime()));
        mmap.put("taskEndTimeStr", this.convertDate1(task.getTaskEndTime()));

        //回显部门
        mmap.put("user", iUserService.selectUserById(task.getUserId()));

        //回显全部部门和用户
        mmap.put("depts", iDeptService.selectDeptList(new Dept()));
        mmap.put("users", iUserService.selectUserList(new User()));
        return prefix + "/edit";
    }

    /**
     * 修改保存公告类别
     */
    @RequiresPermissions("cyq:task:edit")
    @Log(title = "任务管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Task task,String taskStartTime,String taskEndTime)
    {
        if (UserConstants.CYQ_TASK_TITLE_NOT_UNIQUE.equals(iTaskService.checkTaskNameUnique(task)))
        {
            return error("修改公告类别'" + task.getTaskTitle() + "'失败，任务标题已存在");
        }
        return toAjax(iTaskService.updateTask(task,taskStartTime,taskEndTime));
    }


    /**
     * 跳转查看页面
     * @param taskId
     * @param mmap
     * @return
     */
    @GetMapping("/check/{taskId}")
    public String checkTask(@PathVariable("taskId") long taskId, ModelMap mmap) {
        Task task = iTaskService.selectTaskById(taskId);

        //回显一个任务状态
        Status status = new Status();
        status.setTaskStatus(task.getTaskStatus());
        mmap.put("status",statusMapper.selectStatusList(status));

        //回显所有任务状态
        Status status1 = new Status();
        mmap.put("statuss",statusMapper.selectStatusList(status1));

        //回显 任务处理时间、创建时间
        mmap.put("createTime",this.convertDate2(task.getCreateTime()));
        mmap.put("taskEndTime",this.convertDate2(task.getTaskEndTime()));
        mmap.put("taskStartTime",this.convertDate2(task.getTaskStartTime()));

        mmap.put("createTimeValue",this.convertDate1(task.getCreateTime()));
        mmap.put("taskEndTimeValue",this.convertDate1(task.getTaskEndTime()));
        mmap.put("taskStartTimeValue",this.convertDate1(task.getTaskStartTime()));


        //回显执行人员
        mmap.put("user",iUserService.selectUserById(task.getUserId()));


        //回显紧急程度
        Leave leave = new Leave();
        leave.setTaskLeave(task.getTaskLeave());
        List<Leave> leaves = leaveMapper.selectLeaveList(leave);
        mmap.put("leave",leaves.get(0));


        //回显 标题 、任务内容 、完成情况
        mmap.put("task",task);


        return prefix + "/taskcheck";
    }

    /**
     * 转换日期成字符串
     * @param date
     * @return
     */
    public String convertDate1(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date).replace(" ", "T");
    }

    /**
     * 转换字符串成日期
     * @param date
     * @return
     */
    public String convertDate2(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date).replace(" ", "T");
    }


    /** 删除公告类型  */
    @RequiresPermissions("cyq:task:remove")
    @Log(title = "任务管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            return toAjax(iTaskService.deleteTaskByIds(ids));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }


    /**
     * 跳转任务接受查看
     * @return
     */
    @RequiresPermissions("cyq:taskaccept:check")
    @GetMapping("/accept")
    public String taskAccept() {
        return prefix + "/taskaccept";
    }


    /**
     * 任务接受展示页面
     * @param task
     * @return
     */
    @RequiresPermissions("cyq:task:list")
    @PostMapping("/list1")
    @ResponseBody
    public TableDataInfo list1(Task task) {
        startPage();
        List<TaskVo> list = iTaskService.selectTaskList1(task);
        return getDataTable(list);
    }

    /**
     * 跳转任务下发查看
     * @return
     */
    @RequiresPermissions("cyq:task:issue")
    @GetMapping("/issue")
    public String taskIssue() {
        return prefix + "/taskissue";
    }

    /**
     * 任务接受展示页面
     * @param task
     * @return
     */
    @RequiresPermissions("cyq:task:list")
    @PostMapping("/list2")
    @ResponseBody
    public TableDataInfo list2(Task task) {
        startPage();
        List<TaskVo> list = iTaskService.selectTaskList2(task);
        return getDataTable(list);
    }

    /**
     * 查看下发页面
     * @param taskId
     * @param mmap
     * @return
     */
    @GetMapping("/checkissue/{taskId}")
    public String checkTaskIssue(@PathVariable("taskId") long taskId, ModelMap mmap) {
        Task task = iTaskService.selectTaskById(taskId);


        //回显所有任务状态
        Status status1 = new Status();
        mmap.put("statuss",statusMapper.selectStatusList(status1));

        //回显 任务处理时间、创建时间
        mmap.put("createTime",this.convertDate2(task.getCreateTime()));
        mmap.put("taskEndTime",this.convertDate2(task.getTaskEndTime()));
        mmap.put("taskStartTime",this.convertDate2(task.getTaskStartTime()));

        mmap.put("createTimeValue",this.convertDate1(task.getCreateTime()));
        mmap.put("taskEndTimeValue",this.convertDate1(task.getTaskEndTime()));
        mmap.put("taskStartTimeValue",this.convertDate1(task.getTaskStartTime()));


        //回显下发人员
        mmap.put("user",iUserService.selectUserById(task.getTaskIssueUserId()));


        //回显紧急程度
        Leave leave = new Leave();
        leave.setTaskLeave(task.getTaskLeave());
        List<Leave> leaves = leaveMapper.selectLeaveList(leave);
        mmap.put("leave",leaves.get(0));


        //回显 标题 、任务内容 、完成情况
        mmap.put("task",task);


        return prefix + "/taskissuecheck";
    }



    @RequiresPermissions("cyq:task:submit")
    @GetMapping("/resultupload")
    public String  showresultload(){
        return  prefix + "/resultupload";
    }

}
